package com.rainszj.aspect;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

// 标注这个类是一个切面

@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 定义一个切面，拦截controller包下的的所有类的所有方法，方法返回值为任意
     */
    @Pointcut("execution(* com.rainszj.controller.*.*(..))")
    public void pointCut() {

    }

    /**
     * 方法执行之前
     */
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        // 获取 HttpServletRequest
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String ip = request.getRemoteAddr();
        String url = request.getRequestURL().toString();
        // 获取方法头
        Signature signature = joinPoint.getSignature();
        String classMethod = signature.getDeclaringTypeName() + "." + signature.getName();
        Object[] args = joinPoint.getArgs();

        // 封装
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);

        logger.info("[Request] => {}", requestLog);
    }

    /**
     * 方法执行之后
     */
    @After("pointCut()")
    public void doAfter() {
        // logger.info("doAfter.........");
    }

    @AfterReturning(returning = "object", pointcut = "pointCut()")
    public void doAfterReturn(Object object) {
        logger.info("[doAfterReturn] => {}", object);
    }

    /**
     * 封装请求的类
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private class RequestLog {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

    }


}
